<template>
  <el-dialog
    :visible.sync="visible"
    :before-close="beforeClose"
    :close-on-click-modal="false"
    append-to-body
    title="项目查询"
    class="dialog-sm"
    top="30px"
    width="80%"
  >
    <el-form @keyup.enter.native="getData()" :inline="true">
      <el-form-item>
        <el-input
          v-model="params.customer_name"
          clearable
          placeholder="项目名称查询"
          @change="getData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="params.corp_name"
          clearable
          placeholder="负责人查询"
          @change="getData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <select-address
          v-model="params.address_code"
          auto-top
          placeholder="地区查询"
          clearable
          @change="getData()"
        ></select-address>
      </el-form-item>
      <el-form-item>
        <el-button @click="getData()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button @click="clearFilter()">重置</el-button>
      </el-form-item>
    </el-form>

    <c-table
      border
      v-loading="loading"
      :stripe="false"
      :columns="tableColumns"
      :data="tableData"
      height="70vh"
      ref="filterTable"
      @filter-change="handleFilterChange"
    >
      <template v-slot:customerName="scope">
        <div
          class="text-primary cursor-pointer project-history"
          :data-history="scope.row.is_history"
          @click="handleEdit(scope.row)"
        >
          {{ scope.row.customer_name }}
        </div>
      </template>
      <template v-slot:archiveStatus="scope">
        <div :class="scope.row.archiveStatusStyle">{{ scope.row.archiveStatusLabel }}</div>
      </template>
      <template v-slot:recommendStatus="scope">
        <el-tooltip
          effect="light"
          placement="bottom-start"
          :enterable="false"
          :disabled="!scope.row.hasRecommend"
        >
          <div :class="scope.row.recommendStyle">
            <span>{{ scope.row.recommendStatusLabel }}</span>
            <small>
              <i
                v-show="scope.row.hasRecommend"
                class="fa fa-caret-down ml-1 badge-caret-right"
              ></i>
            </small>
          </div>
          <div slot="content">
            <small class="text-muted">{{ scope.row.recommendTime }}</small>
            <br />
            <span>{{ scope.row.recommend_opinion || '-' }}</span>
          </div>
        </el-tooltip>
      </template>
      <template v-slot:acceptStatus="scope">
        <el-tooltip
          effect="light"
          placement="bottom-start"
          :enterable="false"
          v-if="scope.row.hasAcceptRefuse"
        >
          <div :class="scope.row.acceptStyle" class="badge-caret">
            <span>{{ scope.row.acceptStatusLabel }}</span>
            <small><i class="fa fa-caret-down ml-1 badge-caret-right"></i></small>
          </div>
          <div slot="content">
            <span>{{ scope.row.acceptRefuseReason }}</span>
          </div>
        </el-tooltip>
        <div v-else>
          <span :class="scope.row.acceptStyle">{{ scope.row.acceptStatusLabel }}</span>
          <p v-if="scope.row.acceptOrgName && !isBank" class="status-hint">
            <small class="text-muted">{{ scope.row.acceptOrgName }}</small>
          </p>
        </div>
      </template>
      <template v-slot:loanStatus="scope">
        <div>
          <span :class="scope.row.loanStyle">{{ scope.row.loanStatusLabel }}</span>
          <p v-if="scope.row.loanTime" class="status-hint">
            <small class="text-muted">
              {{ $utils.dateFormat(scope.row.loanTime, 'yyyy.MM.dd') }}
            </small>
          </p>
          <p v-if="scope.row.loanFunds" class="status-hint">
            <small class="text-muted">{{ scope.row.loanFunds }}万元</small>
          </p>
          <p v-if="scope.row.confuse" class="status-hint">
            <small class="text-muted">{{ scope.row.confuse }}</small>
          </p>
        </div>
      </template>
      <template v-slot:behindStatus="scope">
        <div>
          <span :class="scope.row.behindStyle">{{ scope.row.behindStatusLabel }}</span>
          <p v-if="scope.row.behindText" class="status-hint">
            <small :class="scope.row.behindTextStyle">{{ scope.row.behindText }}</small>
          </p>
        </div>
      </template>
    </c-table>

    <div class="query-pagination">
      <div></div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="tableCount"
        @current-change="getData"
      ></el-pagination>
    </div>

    <el-dialog
      :visible.sync="reportVisible"
      :close-on-click-modal="false"
      append-to-body
      top="30px"
      width="80%"
    >
      <credit-credit-file
        :query-id="queryId"
        @save="handleEditSuccess"
        :viewMode="true"
        v-if="isCredit && !isHnd"
      ></credit-credit-file>
      <gov-credit-file
        :query-id="queryId"
        @save="handleEditSuccess"
        :viewMode="true"
        v-else-if="isGov && !isHnd"
      ></gov-credit-file>
      <bank-credit-file
        :query-id="queryId"
        :viewMode="true"
        @save="handleEditSuccess"
        v-else-if="isBank && !isHnd"
      ></bank-credit-file>
      <industry-credit :relatedId="queryId" :guaType="guaType" v-if="isHnd"></industry-credit>
    </el-dialog>
  </el-dialog>
</template>
<script>
import { mapGetters } from 'vuex'

import SelectAddress from '@/components/select/SelectAddress'
import IndustryCredit from '@/bank/components/IndustryCredit'
import CreditCreditFile from '@/credit/components/creditFile/CreditCard'
import GovCreditFile from '@/gov/components/creditFile/GovCredit'
import BankCreditFile from '@/bank/components/creditFile/BankCredit'
import { enumProjectNode } from '@/credit/plugins/enumTown'
import {
  enumRecommendStatus,
  // enumPreApproval,
  // enumBankApproval,
  // enumReApproval,
  // enumApprovalRegister,
  // enumReinsuranceStatus,
  // enumProjectType,
  enumRenewalStatus,
} from '@/gov/plugins/enum'

const enumRecommendStyle = {
  0: 'warning',
  1: 'success',
  2: 'danger',
}

const enumRenewalTextStatus = {
  0: 'text-muted',
  1: 'text-muted',
  2: 'text-info',
  3: 'text-primary',
  4: 'text-warning',
  5: 'text-danger',
  6: 'text-success',
}

export default {
  components: {
    CreditCreditFile,
    GovCreditFile,
    BankCreditFile,
    SelectAddress,
    IndustryCredit,
  },
  props: {
    visible: Boolean,
  },
  data() {
    return {
      enumProjectNode,
      loading: false,
      params: {
        index: 1,
        size: 15,
        isBIQuery: 1,
        address_code: '',
        customer_name: '',
        corp_name: '',
      },
      order: {},
      tableName: 'customer_related_one_view',
      tableCount: 0,
      tableData: [],
      tableColumns: [
        {
          attrs: { label: '项目名称', prop: 'customer_name', align: 'center' },
          slot: 'customerName',
        },
        { attrs: { label: '负责人姓名', prop: 'corp_name', align: 'center' } },
        { attrs: { label: '地址', prop: 'address', align: 'center', minWidth: 120 } },
        { attrs: { label: '联系电话', prop: 'mobile_no', align: 'center' } },
        // { attrs: { label: '项目类型', prop: 'project_type', align: 'center' }, process: v => enumProjectType[v] || '-' },
        {
          attrs: {
            label: '是否建档',
            align: 'center',
            prop: 'project_status',
            columnKey: 'project_status',
            filters: [
              { text: '未建档', value: 0 },
              { text: '已建档', value: 1 },
            ],
          },
          slot: 'archiveStatus',
        },
        {
          attrs: {
            label: '是否推荐',
            align: 'center',
            prop: 'recommend_status',
            columnKey: 'recommend_status',
            filters: [
              { text: '未推荐', value: 0 },
              { text: '已推荐', value: 1 },
              { text: '不推荐', value: 2 },
            ],
          },
          slot: 'recommendStatus',
        },
        {
          attrs: {
            label: '是否受理',
            align: 'center',
            prop: 'accept_status',
            columnKey: 'accept_status',
            filters: [
              { text: '未受理', value: 0 },
              { text: '已受理', value: 1 },
              { text: '已拒绝', value: 2 },
            ],
          },
          slot: 'acceptStatus',
        },
        {
          attrs: {
            label: '是否放款',
            align: 'center',
            prop: 'loan_notice_status',
            columnKey: 'loan_notice_status',
            filters: [
              { text: '未放款', value: 0 },
              { text: '已放款', value: 1 },
            ],
          },
          slot: 'loanStatus',
        },
        {
          attrs: {
            label: '是否完结',
            align: 'center',
            prop: 'load_beh_status',
            columnKey: 'load_beh_status',
            filters: [
              { text: '在保中', value: 0 },
              { text: '已完结', value: 1 },
            ],
          },
          slot: 'behindStatus',
        },
      ],

      // 档案卡
      reportVisible: false,
      queryId: '',

      filters: {},
      filterParams: {},

      isHnd: false,
      guaType: 3,
    }
  },
  computed: {
    ...mapGetters(['user', 'clientId']),
    orgClass() {
      return this.user.clientOrgClass
    },
    isGov() {
      return this.orgClass === 'org_gov_ny'
    },
    isBank() {
      return this.orgClass === 'org_bank'
    },
    isCredit() {
      return this.orgClass === 'org_credit'
    },
    queryAddressCode() {
      return this.user.queryAddressCode
    },
    orgRegionLever() {
      return +this.user.orgRegionLever
    },
  },
  watch: {},
  created() {
    this.params.address_code = this.queryAddressCode
    this.getData()
  },
  mounted() {},
  methods: {
    beforeClose() {
      this.$emit('update:visible', false)
    },
    async getData(index = 1) {
      this.params.index = index
      this.loading = true
      const [res] = await this.$utils.promise(
        this.$api.getData(this.$serviceName, this.tableName, this.getParams(), this.order)
      )
      this.loading = false

      const data = (res && res.data) || {}
      this.tableCount = data.totalCount || 0
      this.tableData = (data.data || []).map(this.statusAdapter)
    },
    getParams() {
      const params = { ...this.params, ...this.filterParams }
      // 大数据根据地址查所有不论来源不论业务类型 2020.4.21
      if (this.isGov) {
        params['submit_type.eq'] = 1
      } else if (this.isBank) {
        params.address_code = this.queryAddressCode
      } else if (this.isCredit) {
        params['orWhere.service_id.eq'] = this.clientId
        params['orWhere.recommend_service.eq'] = this.clientId
      } else {
        params['service_id.eq'] = this.clientId
      }

      return params
    },
    statusAdapter(item) {
      // 是否建档：project_status 项目调查 0 未调查 1 已调查 2 调查中 3 已通过 4 未通过(已拒绝)
      item.projectStatus = +item.project_status
      item.hasArchive = item.projectStatus > 0
      item.archiveStatusLabel = item.hasArchive ? '已建档' : '未建档'
      item.archiveStatusStyle =
        'badge badge-pill badge-' + (item.hasArchive ? 'success' : 'warning')

      // 是否被拒
      item.confuseStatus = +item.confuse_status
      item.hasRefuse = item.confuseStatus === 3

      // 是否推荐：recommend_status 推荐状态 0 待推荐 1 已推荐 2 不推荐
      item.recommendStatus = +item.recommend_status
      item.hasRecommend = item.recommendStatus > 0
      item.hasRecommendPass = item.hasRecommend && item.recommendStatus < 2
      item.recommendStatusLabel = '-'

      item.recommendStatusLabel = enumRecommendStatus[item.recommendStatus] || '-'
      item.recommendTime = this.$utils.dateFormat(item.recommend_time, 'yyyy年MM月dd日')
      item.recommendStyle = `badge badge-pill badge-${
        enumRecommendStyle[item.recommendStatus]
      } badge-caret`

      // 是否受理（初审、受理）
      // 银行受理状态：claim_status 0 未受理 1 已受理 已完成
      item.claimStatus = +item.claim_status
      // 担保初审状态：is_approval 审批登记状态 -1 延迟受理 0 未受理 1 已受理 2 受理拒绝
      item.isApproval = +item.is_approval
      item.hasAcceptRefuse = item.claimStatus === 2 || item.isApproval === 2
      item.hasAcceptPass =
        item.hasRecommendPass &&
        !item.hasRefuse &&
        (item.claimStatus === 1 || item.isApproval === 1 || item.isApproval === -1)
      item.acceptStatusLabel = '-'
      if (item.hasRecommendPass) {
        if (item.hasRefuse) {
          item.hasAcceptRefuse = true
          item.acceptStatusLabel = '已拒绝'
          item.acceptStyle = 'badge badge-pill badge-danger'
          item.acceptRefuseReason = item.confuse_des || '-'
        } else if (item.hasAcceptPass) {
          item.acceptStatusLabel = '已受理'
          item.acceptOrgName = this.getApprovalName(item) || ''
          item.acceptStyle = 'badge badge-pill badge-success'
        } else {
          item.acceptStatusLabel = '未受理'
          item.acceptStyle = 'badge badge-pill badge-warning'
        }
      }

      // 是否放款：loan_notice_status 放款通知状态(0 待通知 1 已通知 2 已回执)
      item.loanStatus = +item.loan_notice_status
      item.hasLoan = item.hasRecommendPass && item.loanStatus === 2
      item.loanStatusLabel = '-'
      if (item.hasAcceptPass) {
        // 拒绝放入放款登记模块展示
        if (item.hasRefuse) {
          item.loanStatusLabel = '已拒绝'
          item.loanFunds = ''
          item.loanTime = ''
          item.confuse = enumProjectNode[item.confuse_node]
          item.loanStyle = 'badge badge-pill badge-danger'
        } else if (item.hasLoan) {
          item.loanStatusLabel = '已放款'
          item.loanStyle = 'badge badge-pill badge-success'
          item.loanFunds = item.reply_funds || '-'
          item.loanTime = item.load_date || '-'
        } else {
          item.loanStatusLabel = '未放款'
          item.loanStyle = 'badge badge-pill badge-warning'
        }
      }

      // 是否完结：load_beh_status 贷后状态 1 正常 2 关注 3 次级 4 可疑 5 损失 6已完结
      // 走到贷后的条件变为放款通知已回执(loan_notice_status===2)，下面的判断废弃 @20200324
      // 先走到贷后 approval_register_status === 1
      // item.registerStatus = +item.approval_register_status
      item.behindStatus = +item.load_beh_status
      item.behindStatusLabel = '-'
      if (item.hasLoan) {
        if (item.behindStatus === 6) {
          item.behindStatusLabel = '已完结'
          item.behindStyle = 'badge badge-pill badge-success'
        } else {
          item.behindStatusLabel = '在保中'
          item.behindStyle = 'badge badge-pill badge-info'
          item.behindText = enumRenewalStatus[item.behindStatus]
          item.behindTextStyle = enumRenewalTextStatus[item.behindStatus]
        }
      }

      return item
    },
    handleEdit(row) {
      this.isHnd = +row.gua_type === 3 || +row.is_history === 1
      this.guaType = +row.gua_type
      this.queryId = row.customer_related_id
      this.reportVisible = true
    },
    handleEditSuccess() {
      this.getData()
      this.$store.dispatch('getGovTaskCount')
    },
    // 过滤
    clearFilter() {
      this.$refs.filterTable.$children[0].clearFilter()
      this.filters = {}
      this.getFilterData()
    },
    handleFilterChange(filters) {
      for (const key in filters) {
        this.filters[key] = filters[key]
      }
      this.getFilterData()
    },
    getFilterData() {
      this.filterParams = this.getFilterParams()
      this.params.index = 1
      this.getData()
    },
    // 判断银行与担保谁先受理
    // 要确保两个时间格式一致
    getApprovalName(item) {
      return !item.approved_date || item.claim_time <= item.approved_date
        ? item.bank_name
        : item.service_name
    },
    getFilterParams() {
      const params = {}

      // 建档
      const archiveStatus = this.filters.project_status || []
      if (archiveStatus.length === 1) {
        const archiveValue = archiveStatus[0]
        if (archiveValue === 0) {
          params['project_status.eq'] = 0
        } else {
          params['project_status.gt'] = 0
        }
      }

      // 推荐
      const recommendStatus = this.filters.recommend_status || []
      if (recommendStatus.length === 1) {
        params['recommend_status.eq'] = recommendStatus[0]
      } else if (recommendStatus.length === 2) {
        params['orWhere.recommend_status.eq'] = recommendStatus
      }

      // 受理
      const acceptStatus = this.filters.accept_status || []
      if (acceptStatus.length === 1) {
        const acceptValue = acceptStatus[0]
        if (acceptValue === 0) {
          params['claim_status.eq'] = 0
          params['is_approval.eq'] = 0
        } else if (acceptValue === 1) {
          params['recommend_status.eq'] = 1
          params['confuse_status.neq'] = 3
          params['orWhere.claim_status.eq'] = 1
          params['orWhere.is_approval.eq'] = 1
        } else {
          params['recommend_status.eq'] = 1
          params['confuse_status.eq'] = 3
        }
      } else if (acceptStatus.length === 2) {
        if (acceptStatus.includes(0) && acceptStatus.includes(1)) {
          params['is_approval.neq'] = 2
        } else if (acceptStatus.includes(0) && acceptStatus.includes(2)) {
          params['claim_status.neq'] = 1
          params['is_approval.neq'] = 1
        } else {
          params['recommend_status.eq'] = 1
          params['orWhere.claim_status.neq'] = 0
          params['orWhere.is_approval.neq'] = 0
        }
      }

      // 放款
      const loanStatus = this.filters.loan_notice_status || []
      if (loanStatus.length === 1) {
        const loanValue = loanStatus[0]
        if (loanValue === 0) {
          params['claim_status.eq'] = 1
          params['is_approval.eq'] = 1
          params['confuse_status.neq'] = 3
          params['loan_notice_status.eq'] = 0
        } else {
          params['confuse_status.neq'] = 3
          params['loan_notice_status.gt'] = 0
        }
      }

      // 完结
      const behindStatus = this.filters.load_beh_status || []
      if (behindStatus.length === 1) {
        const behindValue = behindStatus[0]
        if (behindValue === 0) {
          params['loan_notice_status.eq'] = 2
          params['load_beh_status.lt'] = 6
        } else {
          params['load_beh_status.eq'] = 6
        }
      }

      return params
    },
  },
}
</script>
<style lang="scss" scoped>
.status-hint {
  line-height: 1;
  margin: 0;
}
.badge-caret {
  padding-right: 17px;
  position: relative;
}

.badge-caret-right {
  position: absolute;
  right: 5px;
}
</style>
